import Taro from "@tarojs/taro";
import utils from "src/utils/utils";




// 图片地址缓存
class ImgCache {

    constructor() {

    }

    // 图片缓存 map 
    // imgMap = new Map();

    // 加载中的图片
    loadingImg: Array<string> = [];

    async get(url): Promise<string> {
        return url;
        const originUrl = `https:${url.replace(/^https?:/, '')}`;
        // 读取数据
        let localPath = await new Promise<string>(async (resolve, reject) => {

            let localPath = Taro.getStorageSync("imgCache_" + utils.md5(originUrl));
            if (!localPath) {

                // 如果当前图片正在加载中
                if (this.loadingImg.includes(originUrl)) {

                    while (!localPath) {
                        await new Promise((resolve) => setTimeout(resolve, 100));
                        localPath = Taro.getStorageSync("imgCache_" + utils.md5(originUrl));
                    }

                } else { // 如果当前图片没有在加载中
                    this.loadingImg.push(originUrl);
                    //本地图片地址
                    console.log("开始下载图片", originUrl);

                    const res = await Taro.downloadFile({
                        url: utils.ossSuffix(originUrl),
                    });
                    console.log("下载图片完成", res);
                    localPath = res.tempFilePath;
                    // 存储数据
                    Taro.setStorageSync("imgCache_" + utils.md5(originUrl), localPath);
                    // 移除加载中的图片
                    this.loadingImg.splice(this.loadingImg.indexOf(originUrl), 1);
                }
            }
            resolve(localPath);
        });
        return localPath;
    }

}

const imgCache = new ImgCache();

export default imgCache;